// 货位数据生成工具
export const generateWarehouseData = (rows = 4, columns = 8, layers = 4, goodsRate = 70) => {
  const slots = {};
  let slotNumber = 1; // 自然数编号从1开始
  
  // 生成所有货位 (使用1基索引)
  for (let layer = 1; layer <= layers; layer++) {
    for (let row = 1; row <= rows; row++) {
      for (let col = 1; col <= columns; col++) {
        const slotId = `${slotNumber}`; // 使用自然数编号
        
        // 根据货物比例生成货物状态
        // 确保当goodsRate为0时不会生成货物，当goodsRate为100时总是生成货物
        const hasGoods = goodsRate > 0 && Math.random() * 100 < goodsRate;
        
        slots[slotId] = {
          id: slotId,
          layer: layer,  // 改为1基索引
          row: row,      // 改为1基索引
          column: col,   // 改为1基索引
          hasGoods: hasGoods,
          goodsInfo: hasGoods ? {
            name: `货物-${slotId}`,
            quantity: Math.floor(Math.random() * 100) + 1,
            weight: (Math.random() * 500 + 50).toFixed(2) + ' kg',
            entryDate: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
          } : null,
          position: {
            x: col - 1,  // 3D位置仍使用0基索引
            y: layer - 1, // 3D位置仍使用0基索引
            z: row - 1   // 3D位置仍使用0基索引
          }
        };
        
        slotNumber++; // 编号递增
      }
    }
  }
  
  return {
    rows,
    columns,
    layers,
    slots,
    totalSlots: rows * columns * layers,
    occupiedSlots: Object.values(slots).filter(s => s.hasGoods).length,
    emptySlots: Object.values(slots).filter(s => !s.hasGoods).length
  };
};

// 更新货位状态
export const updateSlotStatus = (warehouseData, slotId, hasGoods, goodsInfo = null) => {
  const newData = { ...warehouseData };
  
  if (newData.slots[slotId]) {
    newData.slots[slotId] = {
      ...newData.slots[slotId],
      hasGoods,
      goodsInfo: hasGoods ? goodsInfo : null
    };
    
    // 更新统计信息
    newData.occupiedSlots = Object.values(newData.slots).filter(s => s.hasGoods).length;
    newData.emptySlots = Object.values(newData.slots).filter(s => !s.hasGoods).length;
  }
  
  return newData;
};

// 获取占用率
export const getOccupancyRate = (warehouseData) => {
  return ((warehouseData.occupiedSlots / warehouseData.totalSlots) * 100).toFixed(2);
};

// 按层级获取货位统计
export const getLayerStatistics = (warehouseData) => {
  const stats = [];
  
  // 修复：使用1基索引过滤货位
  for (let layer = 1; layer <= warehouseData.layers; layer++) {
    const layerSlots = Object.values(warehouseData.slots).filter(s => s.layer === layer);
    const occupied = layerSlots.filter(s => s.hasGoods).length;
    
    stats.push({
      layer,
      total: layerSlots.length,
      occupied,
      empty: layerSlots.length - occupied,
      occupancyRate: ((occupied / layerSlots.length) * 100).toFixed(2)
    });
  }
  
  return stats;
};